<template>
  <div class="users">
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.realName" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="button-group">
      <el-button type="primary" @click="handleAdd" v-if="hasPermission('system:user:add')">
        <el-icon><Plus /></el-icon>新增用户
      </el-button>
      <el-button type="success" @click="handleExport">导出</el-button>
    </div>

    <div class="card">
      <el-table :data="tableData" v-loading="loading" border>
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="realName" label="姓名" width="120" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="phone" label="手机号" width="150" />
        <el-table-column prop="roles" label="角色" width="200">
          <template #default="{ row }">
            <el-tag v-for="role in row.roles" :key="role" size="small" style="margin-right: 5px;">
              {{ role }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录" width="180" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)" v-if="hasPermission('system:user:edit')">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)" v-if="hasPermission('system:user:delete')">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="handleDialogClose">
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" placeholder="请输入用户名" :disabled="!!form.id" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="realName">
              <el-input v-model="form.realName" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="密码" prop="password" v-if="!form.id">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        
        <el-form-item label="角色" prop="roles">
          <el-select v-model="form.roles" multiple placeholder="请选择角色" style="width: 100%">
            <el-option
              v-for="role in roles"
              :key="role.value"
              :label="role.label"
              :value="role.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio value="active">正常</el-radio>
            <el-radio value="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

const hasPermission = (permission) => {
  return userStore.hasPermission(permission)
}

const searchForm = reactive({
  username: '',
  realName: '',
  status: ''
})

const tableData = ref([])
const loading = ref(false)
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const roles = ref([
  { label: '系统管理员', value: 'admin' },
  { label: '采购员', value: 'purchaser' },
  { label: '仓库管理员', value: 'warehouse' },
  { label: '销售员', value: 'sales' },
  { label: '财务', value: 'finance' }
])

const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const formRef = ref()

const form = reactive({
  id: null,
  username: '',
  realName: '',
  email: '',
  phone: '',
  password: '',
  roles: [],
  status: 'active',
  remark: ''
})

const formRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  roles: [{ required: true, message: '请选择角色', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const mockData = [
  {
    id: 1,
    username: 'admin',
    realName: '系统管理员',
    email: 'admin@example.com',
    phone: '13800138000',
    roles: ['admin'],
    status: 'active',
    lastLoginTime: '2024-01-15 10:30:00',
    createTime: '2024-01-01 00:00:00',
    remark: '系统管理员'
  },
  {
    id: 2,
    username: 'purchaser1',
    realName: '张三',
    email: 'zhangsan@example.com',
    phone: '13800138001',
    roles: ['purchaser'],
    status: 'active',
    lastLoginTime: '2024-01-14 14:20:00',
    createTime: '2024-01-02 00:00:00',
    remark: '采购员'
  },
  {
    id: 3,
    username: 'sales1',
    realName: '李四',
    email: 'lisi@example.com',
    phone: '13800138002',
    roles: ['sales'],
    status: 'active',
    lastLoginTime: '2024-01-13 09:15:00',
    createTime: '2024-01-03 00:00:00',
    remark: '销售员'
  },
  {
    id: 4,
    username: 'warehouse1',
    realName: '王五',
    email: 'wangwu@example.com',
    phone: '13800138003',
    roles: ['warehouse'],
    status: 'active',
    lastLoginTime: '2024-01-12 16:45:00',
    createTime: '2024-01-04 00:00:00',
    remark: '仓库管理员'
  },
  {
    id: 5,
    username: 'finance1',
    realName: '赵六',
    email: 'zhaoliu@example.com',
    phone: '13800138004',
    roles: ['finance'],
    status: 'active',
    lastLoginTime: '2024-01-11 11:20:00',
    createTime: '2024-01-05 00:00:00',
    remark: '财务专员'
  },
  {
    id: 6,
    username: 'manager1',
    realName: '钱七',
    email: 'qianqi@example.com',
    phone: '13800138005',
    roles: ['manager'],
    status: 'active',
    lastLoginTime: '2024-01-10 09:30:00',
    createTime: '2024-01-06 00:00:00',
    remark: '部门经理'
  },
  {
    id: 7,
    username: 'operator1',
    realName: '孙八',
    email: 'sunba@example.com',
    phone: '13800138006',
    roles: ['operator'],
    status: 'inactive',
    lastLoginTime: '2024-01-09 14:15:00',
    createTime: '2024-01-07 00:00:00',
    remark: '操作员（停用）'
  }
]

const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, { username: '', realName: '', status: '' })
  handleSearch()
}

const loadData = () => {
  loading.value = true
  setTimeout(() => {
    tableData.value = mockData
    pagination.total = mockData.length
    loading.value = false
  }, 500)
}

const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadData()
}

const handleAdd = () => {
  dialogTitle.value = '新增用户'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'
  Object.assign(form, {
    id: row.id,
    username: row.username,
    realName: row.realName,
    email: row.email,
    phone: row.phone,
    password: '',
    roles: row.roles,
    status: row.status,
    remark: row.remark
  })
  dialogVisible.value = true
}

const handleView = (row) => {
  ElMessage.info('查看功能开发中...')
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    ElMessage.success('删除成功')
    loadData()
  } catch {}
}

const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    setTimeout(() => {
      ElMessage.success(form.id ? '更新成功' : '创建成功')
      dialogVisible.value = false
      loadData()
      submitLoading.value = false
    }, 1000)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const resetForm = () => {
  Object.assign(form, {
    id: null,
    username: '',
    realName: '',
    email: '',
    phone: '',
    password: '',
    roles: [],
    status: 'active',
    remark: ''
  })
}

const handleDialogClose = () => {
  resetForm()
}

onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.users {
  .pagination-wrapper {
    margin-top: 20px;
    text-align: right;
  }
}
</style> 